package cn.stylefeng.guns.modular.business.frequency.pricelibrary.controller;

import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.enums.ReturnCode;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.AndaPageResult;
import cn.stylefeng.guns.core.pojo.response.AndaSuccessResponseData;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.custom.enums.PriceLibraryStatusEnum;
import cn.stylefeng.guns.modular.business.frequency.pricelibrary.entity.PriceLibrary;
import cn.stylefeng.guns.modular.business.frequency.pricelibrary.model.param.PriceLibraryDTO;
import cn.stylefeng.guns.modular.business.frequency.pricelibrary.model.result.PkgPriceLibrary;
import cn.stylefeng.guns.modular.business.frequency.pricelibrary.service.PriceLibraryService;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.util.EasyExcelUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@Api(tags = "价格库管理")
@RestController
@RequestMapping("/api/price-library")
public class PriceLibraryController {


    @Resource
    private PriceLibraryService priceLibraryService;
    @Autowired
    private BusinessUtil businessUtil;

    @ApiOperation(value = "全部价格库")
    @GetMapping("/all")
    public ResponseData priceLibraryGetAll(PriceLibraryDTO priceLibraryDTO) {
        priceLibraryDTO.setStatus(PriceLibraryStatusEnum.COMMON.status);
        // 排序
        if (StringUtils.isBlank(priceLibraryDTO.getColumn())) {
            priceLibraryDTO.setColumn("CAST( pl.id AS SIGNED )");
            priceLibraryDTO.setAsc(false);
        }
        Long tenantId = businessUtil.getTenantId();
        if (tenantId==null){
            tenantId = 1l;
        }
        Page<PkgPriceLibrary> page  = priceLibraryService.getPriceLibraryListPage(PageFactory.defaultPage(),priceLibraryDTO,tenantId);
        return ResponseData.andaSuccess(new AndaPageResult().AndaPageResult(page, priceLibraryDTO));
    }

    @ApiOperation(value = "我的价格库")
    @GetMapping("/my")
    public ResponseData priceLibraryGetMy(PriceLibraryDTO priceLibraryDTO) {
        priceLibraryDTO.setUserId(LoginContextHolder.me().getSysLoginUserId().toString());
        // 排序
        if (StringUtils.isBlank(priceLibraryDTO.getColumn())) {
            priceLibraryDTO.setColumn("CAST( pl.id AS SIGNED )");
            priceLibraryDTO.setAsc(false);
        }
        Long tenantId = businessUtil.getTenantId();
        Page<PkgPriceLibrary> page  = priceLibraryService.getPriceLibraryListPage(PageFactory.defaultPage(),priceLibraryDTO,tenantId);
        return ResponseData.andaSuccess(new AndaPageResult().AndaPageResult(page, priceLibraryDTO));
    }

    @ApiOperation(value = "待审核价格库")
    @GetMapping("/check")
    public ResponseData priceLibraryGetUncheck( PriceLibraryDTO priceLibraryDTO) {
        priceLibraryDTO.setStatus(PriceLibraryStatusEnum.WAIT_CHECK.status);
        // 排序
        if (StringUtils.isBlank(priceLibraryDTO.getColumn())) {
            priceLibraryDTO.setColumn("CAST( pl.id AS SIGNED )");
            priceLibraryDTO.setAsc(false);
        }
        Long tenantId = businessUtil.getTenantId();
        if (tenantId==null){
            tenantId = 1l;
        }
        Page<PkgPriceLibrary> page  = priceLibraryService.getPriceLibraryListPage(PageFactory.defaultPage(),priceLibraryDTO,tenantId);
        return ResponseData.andaSuccess(new AndaPageResult().AndaPageResult(page, priceLibraryDTO));
    }

    @ApiOperation(value = "价格详情")
    @GetMapping("/{id}")
    public ResponseData priceLibraryDetail(@PathVariable String id) {
        PkgPriceLibrary pl = priceLibraryService.getDetailById(id);
        return ResponseData.success(pl);
    }

    @ApiOperation(value = "价格库新增")
    @PostMapping
    @PreAuthorize("@el.check('price:add')")
    public ResponseData priceLibraryAdd(@RequestBody @Validated PriceLibrary priceLibrary) {
        StringBuilder errorMsg = new StringBuilder();
        if (!priceLibraryService.checkPriceLibraryAdd(priceLibrary, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        priceLibraryService.save(priceLibrary);
        return ResponseData.success();
    }

    @ApiOperation(value = "线路新增")
    @PostMapping("/line")
    @PreAuthorize("@el.check('line:add')")
    public ResponseData lineAdd(@RequestBody @Validated PriceLibrary priceLibrary) {
        StringBuilder errorMsg = new StringBuilder();
        if (!priceLibraryService.checkPriceLibraryAdd(priceLibrary, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        priceLibraryService.addLine(priceLibrary);
        return ResponseData.success();
    }

    @ApiOperation(value = "价格库修改")
    @PutMapping
    @PreAuthorize("@el.check('price:add')")
    public ResponseData priceLibraryUpdate(@RequestBody @Validated PriceLibrary priceLibrary) {
        StringBuilder errorMsg = new StringBuilder();
        if (!priceLibraryService.checkPriceLibraryUpdate(priceLibrary, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        priceLibraryService.updateById(priceLibrary);
        return ResponseData.success();
    }

    @ApiOperation(value = "线路修改")
    @PutMapping("/line")
    @PreAuthorize("@el.check('line:add')")
    public ResponseData lineUpdate(@RequestBody @Validated PriceLibrary priceLibrary) {
        StringBuilder errorMsg =new StringBuilder();
        if (!priceLibraryService.checkPriceLibraryUpdate(priceLibrary, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        priceLibraryService.lineUpdate(priceLibrary);
        return ResponseData.success();
    }

    @ApiOperation(value = "线路审核")
    @PutMapping("/line/check")
    @PreAuthorize("@el.check('line:check')")
    public ResponseData lineCheck(@RequestBody @Validated PriceLibrary priceLibrary) {
        StringBuilder errorMsg = new StringBuilder();
        if (!priceLibraryService.checkPriceLibraryUpdate(priceLibrary, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        priceLibraryService.lineCheck(priceLibrary);
        return ResponseData.success();
    }

    @ApiOperation(value = "价格库删除")
    @DeleteMapping()
    @PreAuthorize("@el.check('price:add')")
    public ResponseData priceLibraryDelete(@RequestBody List<String> ids) {
        priceLibraryService.removeByIds(ids);
        return ResponseData.success("删除成功");
    }

    @ApiOperation(value = "价格库禁用/启用")
    @PutMapping("/disabled/{id}")
    public ResponseData priceLibraryStatusUpdate(@PathVariable String id) {
        priceLibraryService.disableOrStart(id);
        return ResponseData.success();
    }

    /*@ApiOperation(value = "禁用价格库")
    @GetMapping("/disable/page")
    public ResponseData priceLibraryGetDisable(PageDO page, PriceLibraryDTO priceLibraryDTO) {
        priceLibraryDTO.setStatus(PriceLibraryStatusEnum.DISABLED.status);
        PageDO list = priceLibraryService.getPriceLibraryListPage(page, priceLibraryDTO);
        return new ResponseData(ReturnCode.RETURN_SUCCESS, list);
    }*/

    @ApiOperation(value = "价格库搜索")
    @GetMapping("/search")
    public ResponseData priceLibrarySearch(PriceLibraryDTO priceLibraryDTO) {
        // 出发地、目的地
        Long tenantId = businessUtil.getTenantId();
        List<PkgPriceLibrary> result = priceLibraryService.priceLibrarySearch(priceLibraryDTO,tenantId);
        return ResponseData.success(result);
    }

    @ApiOperation(value = "价格库导出")
    @GetMapping("/export")
    @PreAuthorize("@el.check('price:export')")
    public void export(HttpServletResponse response) throws Exception {
        EasyExcelUtil.export2Web(response, "价格库", "sheet1",
                PriceLibrary.class, priceLibraryService.getExportDataList());
    }

    @ApiOperation(value = "价格库excel导入")
    @PostMapping("/import-excel")
    @PreAuthorize("@el.check('price:import')")
    public ResponseData importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        priceLibraryService.importExcel(file);
        return AndaSuccessResponseData.success("导入成功");
    }

    @ApiOperation(value = "提送车价格分页列表")
    @GetMapping("/pick-take-price/page")
    public ResponseData getPickTakePriceListPage( PriceLibraryDTO pickTakePriceDTO) {
        if (StringUtils.isNotBlank(pickTakePriceDTO.getAreaCode())) {
            if (pickTakePriceDTO.getAreaCode().endsWith("00")) {
                pickTakePriceDTO.setCityCode(pickTakePriceDTO.getAreaCode());
                pickTakePriceDTO.setAreaCode(null);
            }
        }
        Page page = priceLibraryService.getPickTakePriceListPage(pickTakePriceDTO);
        return new AndaSuccessResponseData( page);
    }

    @ApiOperation(value = "根据提车区域查询提车费")
    @GetMapping("/pick-fee")
    public ResponseData getPickFee(PriceLibraryDTO pickTakePriceDTO) {
        if (pickTakePriceDTO == null || StringUtils.isBlank(pickTakePriceDTO.getAreaCode()) || pickTakePriceDTO.getPickCarType() == null) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,"参数错误");
        }
        BigDecimal fee = priceLibraryService.getPickFeeByAreaCode(pickTakePriceDTO);
        return ResponseData.success(fee);
    }

    @ApiOperation(value = "根据送车区域查询送车费")
    @GetMapping("/take-fee")
    public ResponseData getTakeFee(PriceLibraryDTO pickTakePriceDTO) {
        if (pickTakePriceDTO == null || StringUtils.isBlank(pickTakePriceDTO.getAreaCode()) || pickTakePriceDTO.getTakeCarType() == null) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,"参数错误");
        }
        BigDecimal fee = priceLibraryService.getTakeFeeByAreaCode(pickTakePriceDTO);
        return ResponseData.success(fee);
    }

/*    @ApiOperation(value = "提送车价格修改")
    @PutMapping("/pick-take-price")
    @PreAuthorize("@el.check('price:add')")
    public ResponseData updatePickTakePrice(@RequestBody PickTakePrice pickTakePrice) {
        priceLibraryService.updatePickTakePrice(pickTakePrice);
        return ResponseData.andaSuccess();
    }*/

    @ApiOperation(value = "获取路线最低的一个价格")
    @GetMapping("/minimum")
    public ResponseData getMinimumPrice(PriceLibraryDTO priceLibraryDTO) {
        PkgPriceLibrary pl = priceLibraryService.getMinimumPrice(priceLibraryDTO);
        return ResponseData.andaSuccess(pl);
    }
}


